<template>
  <Page title="答题卡" :on-page-back="onPageBack">
    <template #navBarCustom>
      <div class="flex items-center navBox">
        <div class="back" @click="back">
          <img class="icon" src="static/icons/back.png" mode="" />
          <span style="color: #fff">答题卡</span>
        </div>
      </div>
    </template>
    <template #content>
      <div class="w-full h-full p-20px box-border">
        <div
          class="container w-full h-full bg-white flex flex-col overflow-hidden pt-0px box-border"
        >
          <div class="list px-0px box-border flex-1 overflow-scroll" style="font-size: 0">
            <span
              class="item flex-center relative"
              :class="!i.localStudentAnswerStatus ? 'bg-FF4040-10' : 'bg-71C0FA-10'"
              v-for="(i, index) in questions"
              :key="index"
              @click="showTheQuestion(index)"
            >
              <span class="text-666666">第</span
              ><span class="index font-bold text-333">{{ index + 1 }}</span
              ><span class="text-666666">题</span>
              <span
                class="no-answer absolute text-white py-5px px-8px bg-FF4040"
                v-show="!i.localStudentAnswerStatus"
                >未作答</span
              >
              <span
                class="answered absolute text-white py-5px px-8px bg-51C3FF"
                v-show="i.localStudentAnswerStatus"
                >已作答</span
              >
            </span>
          </div>
          <div class="submit">
            <CustomButton class="block" @click="submit">提交</CustomButton>
          </div>
        </div>
      </div>
    </template>
  </Page>
</template>

<script>
// import Page from '@/components/page'
import Page from '@/components/page/newPage'
import CustomButton from '@/components/button'
import { upExamQuestionAnswerApi } from '@/api/homework'
import { mapState } from 'vuex'
import { creatEexceptionAnalysisApi } from '@/api/common'

export default {
  components: {
    Page,
    CustomButton
  },
  data() {
    return {
      // 累计时间
      cumulativeTime: {
        vm: this._self,
        timeout: null,
        // 单位：秒
        value: 0,
        // 累加
        run: function () {
          this.timeout = setTimeout(() => {
            const beginTime = this.vm.currentHomework.record.beginTime
            const endTime = this.vm.currentHomework.record.endTime

            if (beginTime && endTime) {
              const endTimestamp = new Date(endTime).getTime()
              const nowTime = new Date().getTime()
              if (nowTime >= endTimestamp) {
                this.vm.submit(true)
                this.vm.$popup.show({
                  type: 'alert',
                  success: (popup) => {
                    popup.$on('confirm', () => {
                      this.vm.$popup.hide('alert')
                    })
                    popup.setData({
                      content: '已超过作答时间，作业已自动提交'
                    })
                  }
                })
              }
            }

            this.value++
            this.run()
          }, 1000)
        },
        reset: function () {
          clearTimeout(this.timeout)
          this.value = 0
        }
      }
    }
  },
  computed: {
    ...mapState(['homework']),
    currentHomework() {
      return this.homework.currentHomework
    },
    questions() {
      const { questions } = this.homework.currentHomework

      return questions
    }
  },
  mounted() {
    console.log(this.homework.currentHomework)
    this.cumulativeTime.run()
  },
  beforeDestroy() {
    this.cumulativeTime.reset()
  },
  methods: {
    back() {
      this.$router.go(-1)
    },
    showTheQuestion(index) {
      const { currentHomework } = this.homework

      currentHomework.questionIndex = index

      this.$router.replace('/pages/homework/todo/question/xkw/index')
    },
    submit(force = false) {
      const {
        record: { id },
        questions
      } = this.homework.currentHomework

      const _submit = (questions) => {
        const loading = this.$loading({
          lock: true,
          text: '提交答案...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.5)'
        })
        // 一分钟内上传不成功关闭loading弹窗
        const timer = setTimeout(() => {
          loading.close()
        }, 60000)
        const submitItem = async (questions) => {
          if (questions.length > 0) {
            const { answerScoreable, localStudentAnswer: nextItem } = questions.shift()

            let formdata = nextItem
            if (answerScoreable) {
              const copyNextItem = JSON.parse(JSON.stringify(nextItem))
              copyNextItem.studentAnswer = JSON.stringify(copyNextItem.studentAnswer)
              formdata = copyNextItem
            }

            await upExamQuestionAnswerApi(formdata)
            // 如果单道题做题时间不足10秒，创建异常分析
            if (formdata.studentDuration < 10) {
              const {
                record: { examCode = '', examName, subject, createTime }
              } = this.currentHomework
              // 只上传作业异常分析
              if (!examCode) {
                await creatEexceptionAnalysisApi({
                  type: '1',
                  exceptionDay: this.$utils.parseTime(createTime, '{y}-{m}-{d}'),
                  title: examName,
                  subject
                })
              }
            }
            submitItem(questions)
          } else {
            clearTimeout(timer)
            loading.close()
            this.$message.success('提交成功')
            this.$router.replace('/pages/homework/detail/question/xkw/index')
            this.$nextTick(() => this.$storage.homework.deleteCacheItem(id))
          }
        }

        submitItem(JSON.parse(JSON.stringify(questions)))
      }

      // 强制提交
      if (force) {
        _submit(questions)
        return
      }

      if (Array.isArray(questions)) {
        const unAnswerArr = questions.filter((i) => i.localStudentAnswerStatus === 0)
        const unAnswerCount = unAnswerArr.length

        if (unAnswerCount > 0) {
          this.$popup.show({
            type: 'confirm',
            success: (popup) => {
              popup.$on('cancel', () => {
                this.$popup.hide('confirm')
              })
              popup.$on('confirm', () => {
                this.$popup.hide('confirm')
                _submit(questions)
              })
              popup.setData({
                content: '存在未作答的题目，确认提交？'
              })
            }
          })
        } else {
          this.$popup.show({
            type: 'confirm',
            success: (popup) => {
              popup.$on('cancel', () => {
                this.$popup.hide('confirm')
              })
              popup.$on('confirm', () => {
                this.$popup.hide('confirm')
                _submit(questions)
              })
              popup.setData({
                content: '确认提交？'
              })
            }
          })
        }
      }
    },
    onPageBack() {
      this.$router.replace('/pages/homework/todo/question/xkw/index')
    }
  }
}
</script>

<style lang="scss" scoped>
.navBox {
  padding: 0 20px;
  box-sizing: border-box;
}
.back {
  height: 100%;
  display: flex;
  align-items: center;
  font-size: 28px;

  .icon {
    width: 17.14px;
    height: 30px;
    margin-right: 11px;
  }
}
.container {
  // border-radius: 16px;
  .submit {
    .block {
      width: 450px;
      margin: 0 auto;
      font-size: 28px;
    }
  }
}

.list {
  display: inline-grid;
  align-content: flex-start;
  grid-template-columns: 190px 190px 190px 190px 190px 190px;
  grid-column-gap: 20px;
  grid-row-gap: 20px;

  .item {
    width: 190px;
    height: 100px;
    font-size: 28px;
    line-height: 36px;
    border-radius: 8px;

    .index {
    }

    .no-answer,
    .answered {
      top: 0;
      left: 0;
      font-size: 22px;
      line-height: 22px;
      border-radius: 8px 0px 15px 0px;
    }
  }
}
</style>
